package com.dson.user.service.impl;

import com.dson.common.pojo.UserResult;
import com.dson.common.service.UserService;
import com.dson.user.pojo.User;
import com.dson.user.repository.UserRepository;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Optional;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserResult verifyToken(String token) {
        User user = userRepository.getByToken(token);
        return  createUserResult(user);
    }

    @Override
    public boolean checkEmail(String email) {
        return Optional.ofNullable(userRepository.getByEmail(email)).isPresent();
    }

    @Override
    public UserResult login(String email, String password) {
        User user = userRepository.getByEmailAndPassword(email, password);
        if (user == null) {
            return null;
        }

        user.setToken(UUID.randomUUID().toString());
        userRepository.save(user);

        return createUserResult(user);

    }

    @Override
    public UserResult register(String email, String password) {
        String token = UUID.randomUUID().toString();
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        user.setToken(token);
        userRepository.save(user);


        return createUserResult(user);
    }

    private  UserResult createUserResult(User user){
        UserResult userResult = new UserResult();
        userResult.setEmail(user.getEmail());
        userResult.setToken(user.getToken());

        return userResult;
    }
}
